package com.adminx.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.adminx.dao.CodeDao;
import com.adminx.entity.Code;
import com.adminx.pojo.CodePojo;
import com.adminx.util.PageResults;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class CodeService {
	
	
	@Autowired
	private CodeDao codeDao;
	
	/**
	 * 分页查找
	 */
	public PageResults<CodePojo> queryValueCode(Integer pageIndex, Integer pageSize, String searchText){
		return this.codeDao.queryValueCode(pageIndex, pageSize, searchText);
	}
	
	/**
	 * 分页查找子集
	 */
	public PageResults<CodePojo> queryValueDetail(Integer pageIndex, Integer pageSize, Long codeId){
		return this.codeDao.queryValueDetail(pageIndex, pageSize, codeId);
	}
	
	/**
	 * 批量删除
	 */
	public int delBatch(String ids){
		return this.codeDao.delBatch(ids);
	}
	
	/**
	 * 通过ID查询code
	 */
	public Code info(Long codeId) {
		String hql = "From Code t where t.codeId = ?";
		return this.codeDao.getByHQL(hql,codeId);
	}
	
	/**
	 * 新增/修改值集
	 * @param code
	 */
	public void save(Code code){
		//新增
		if(code.getCodeId() == null){
			String sql = "SELECT CONCAT('CODE',LPAD(max(SUBSTR(c.`code`,5,3)+1),3,'0')) FROM `xx_code` c";
			Object object = codeDao.getSession().createSQLQuery(sql).uniqueResult();
			String code1 = object == null ? "CODE001": object.toString();
			code.setCode(code1);
			code.setStatus(1);
			this.codeDao.save(code);
		}
		//修改
		else{
			Code oldCode = this.codeDao.get(code.getCodeId());
			oldCode.setCodeName(code.getCodeName());
			oldCode.setCode(code.getCode());
			oldCode.setRemark(code.getRemark());
			oldCode.setUpdateDate(new Date());
			oldCode.setCreateDate(code.getCreateDate());
			this.codeDao.update(oldCode);
		}
	}
	
	public void ban(Long id){
		this.codeDao.ban(id);
	}
}
